<template>
  <div class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50" @click="handleBackdropClick">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-2/3 shadow-lg rounded-md bg-white max-h-[80vh] overflow-y-auto">
      <!-- 标题 -->
      <div class="flex items-center justify-between mb-6">
        <h3 class="text-lg font-medium text-gray-900">
          {{ $t('sighting.modalTitle', { name: post.pet?.name }) }}
        </h3>
        <button
          @click="$emit('close')"
          class="text-gray-400 hover:text-gray-600"
        >
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center py-12">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
      </div>

      <!-- 线索列表 -->
      <div v-else-if="sightings.length > 0" class="space-y-6">
        <div
          v-for="sighting in sightings"
          :key="sighting.id"
          class="border border-gray-200 rounded-lg p-6"
        >
          <div class="flex items-start justify-between mb-4">
            <div class="flex items-center space-x-2">
              <h4 class="text-sm font-medium text-gray-900">
                {{ $t('sighting.sightingId', { id: sighting.id }) }}
              </h4>
              <span
                :class="[
                  'px-2 py-1 text-xs font-medium rounded-full',
                  sighting.is_verified
                    ? 'bg-green-100 text-green-800'
                    : 'bg-gray-100 text-gray-800'
                ]"
              >
                {{ sighting.is_verified ? $t('sighting.verified') : $t('sighting.pending') }}
              </span>
            </div>
            <div class="flex items-center space-x-2">
              <button
                @click="toggleVerification(sighting)"
                :class="[
                  'text-xs font-medium px-3 py-1 rounded-md',
                  sighting.is_verified
                    ? 'bg-gray-200 text-gray-700 hover:bg-gray-300'
                    : 'bg-green-600 text-white hover:bg-green-700'
                ]"
              >
                {{ sighting.is_verified ? $t('sighting.cancelVerification') : $t('sighting.markAsVerified') }}
              </button>
            </div>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- 线索信息 -->
            <div class="space-y-3">
              <div>
                <dt class="text-sm font-medium text-gray-500">{{ $t('sighting.sightingTime') }}</dt>
                <dd class="mt-1 text-sm text-gray-900">{{ formatDate(sighting.sighting_time) }}</dd>
              </div>
              <div>
                <dt class="text-sm font-medium text-gray-500">{{ $t('sighting.sightingLocation') }}</dt>
                <dd class="mt-1 text-sm text-gray-900">{{ sighting.sighting_location }}</dd>
              </div>
              <div v-if="sighting.description">
                <dt class="text-sm font-medium text-gray-500">{{ $t('sighting.sightingDescription') }}</dt>
                <dd class="mt-1 text-sm text-gray-900">{{ sighting.description }}</dd>
              </div>
              <div>
                <dt class="text-sm font-medium text-gray-500">{{ $t('sighting.submittedAt') }}</dt>
                <dd class="mt-1 text-sm text-gray-900">{{ formatDate(sighting.created_at) }}</dd>
              </div>
            </div>

            <!-- 线索照片 -->
            <div v-if="sighting.sighting_photo_url">
              <dt class="text-sm font-medium text-gray-500 mb-2">{{ $t('sighting.sightingPhoto') }}</dt>
              <img
                :src="getFullImageUrl(sighting.sighting_photo_url)"
                :alt="$t('sighting.sightingPhoto')"
                class="w-full h-48 object-cover rounded-lg cursor-pointer"
                @click="openImageModal(getFullImageUrl(sighting.sighting_photo_url))"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="text-center py-12">
        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
        </svg>
        <h3 class="mt-2 text-sm font-medium text-gray-900">{{ $t('sighting.noSightings') }}</h3>
        <p class="mt-1 text-sm text-gray-500">
          {{ $t('sighting.noSightingsDescription') }}
        </p>
      </div>

      <!-- 分页 -->
      <div v-if="pagination.totalPages > 1" class="mt-6">
        <Pagination
          :current-page="pagination.page"
          :total-pages="pagination.totalPages"
          :total="pagination.total"
          @page-change="handlePageChange"
        />
      </div>

      <!-- 关闭按钮 -->
      <div class="flex justify-end mt-6">
        <button
          @click="$emit('close')"
          class="btn-secondary"
        >
          {{ $t('common.close') }}
        </button>
      </div>
    </div>

    <!-- 图片查看模态框 -->
    <div
      v-if="showImageModal"
      class="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-60"
      @click="closeImageModal"
    >
      <div class="max-w-4xl max-h-full p-4">
        <img
          :src="selectedImage"
          :alt="$t('sighting.sightingPhoto')"
          class="max-w-full max-h-full object-contain"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { sightingService } from '@/services/sightings'
import Pagination from '@/components/Pagination.vue'
import { formatDate, getFullImageUrl } from '@/utils/helpers'
import type { Post, Sighting } from '@/types'
import { PAGINATION } from '@/constants'

interface Props {
  post: Post
}

interface Emits {
  (e: 'close'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { t } = useI18n()

// 状态
const loading = ref(false)
const sightings = ref<Sighting[]>([])
const pagination = ref({
  page: 1,
  limit: PAGINATION.DEFAULT_LIMIT,
  total: 0,
  totalPages: 0,
})

// 图片查看相关状态
const showImageModal = ref(false)
const selectedImage = ref('')

// 方法
const handleBackdropClick = (event: MouseEvent) => {
  if (event.target === event.currentTarget) {
    emit('close')
  }
}

const loadSightings = async () => {
  try {
    loading.value = true

    const response = await sightingService.getPostSightingsPublic(props.post.id, {
      page: pagination.value.page,
      limit: pagination.value.limit,
    })

    if (response.success && response.data) {
      // 服务器返回的格式是 { success, message, data: [...], pagination: {...} }
      sightings.value = response.data as Sighting[]
      // 从响应中获取分页信息
      if ('pagination' in response) {
        pagination.value = {
          page: (response as any).pagination.currentPage,
          limit: (response as any).pagination.itemsPerPage,
          total: (response as any).pagination.totalItems,
          totalPages: (response as any).pagination.totalPages,
        }
      }
    }
  } catch (error) {
    console.error(t('sighting.loadSightingsFailed'), error)
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  pagination.value.page = page
  loadSightings()
}

const toggleVerification = async (sighting: Sighting) => {
  try {
    const response = await sightingService.verify(sighting.id, !sighting.is_verified)

    if (response.success) {
      sighting.is_verified = !sighting.is_verified
    } else {
      alert(t('sighting.operationFailed', { message: response.message }))
    }
  } catch (error) {
    console.error('验证线索失败:', error)
    alert(t('sighting.operationFailedRetry'))
  }
}

const openImageModal = (imageUrl: string) => {
  selectedImage.value = imageUrl
  showImageModal.value = true
}

const closeImageModal = () => {
  showImageModal.value = false
  selectedImage.value = ''
}

onMounted(() => {
  loadSightings()
})
</script>
